package project.servlets;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.sun.rowset.CachedRowSetImpl;


import schronisko.Queries;

/**
 * Servlet implementation class Search
 */
@WebServlet("/Search")
public class Search extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
	HttpSession session;
	ResultSet result;
	Queries q = new Queries();
    public Search() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		session = request.getSession();
		String all=request.getParameter("all");
		session.setAttribute("all", all);
		if(all.equals("1")){
			result = q.getAnimals();
			CachedRowSetImpl crs = null;
			try {
				crs = new CachedRowSetImpl();
				crs.populate(result);
			} catch (SQLException e) {
				
			}
			
			session.setAttribute("allAnimals", crs);
			session.setAttribute("search", 0);
			response.sendRedirect("Search.jsp");
		}
		else {
			String race = request.getParameter("race");
			String gender = request.getParameter("gender");
			String age = request.getParameter("age");
			String eq = request.getParameter("eq");
			String accessibility = "available";
			result = q.searchAnimal(race, gender, age, eq, accessibility);
			CachedRowSetImpl crs = null;
			try {
				crs = new CachedRowSetImpl();
				crs.populate(result);
			} catch (SQLException e) {
				
			}
			session.setAttribute("animals", crs);
			session.setAttribute("search", 0);
			response.sendRedirect("Search.jsp");
					
		}
	}

}
